package top.houry.limit;

import com.google.common.cache.CacheBuilder;
import com.google.common.cache.CacheLoader;
import com.google.common.cache.LoadingCache;

import java.util.concurrent.ExecutionException;
import java.util.concurrent.TimeUnit;
import java.util.concurrent.atomic.AtomicLong;

public class GuavaRateLimiter {
    private final LoadingCache<Long, AtomicLong> cache;

    public GuavaRateLimiter() {
        this.cache = CacheBuilder.newBuilder()
                .expireAfterWrite(1, TimeUnit.SECONDS) // 每个键的有效期为1秒
                .build(new CacheLoader<Long, AtomicLong>() {
                    @Override
                    public AtomicLong load(Long key) {
                        return new AtomicLong(0);
                    }
                });
    }

    public boolean tryAcquire() throws ExecutionException {
        long now = System.currentTimeMillis() / 1000; // 当前时间秒数
        try {
            AtomicLong count = cache.get(now);
            return count.incrementAndGet() <= 100;
        } catch (ExecutionException e) {
            // 如果加载过程中出现异常，重新尝试获取缓存
            return cache.get(System.currentTimeMillis() / 1000).incrementAndGet() <= 100;
        }
    }

    public static void main(String[] args) {
        GuavaRateLimiter rateLimiter = new GuavaRateLimiter();

        try {
            for (int i = 0; i < 150; i++) {
                boolean result = rateLimiter.tryAcquire();
                System.out.println("请求 " + i + ": " + (result ? "通过" : "拒绝"));
//                Thread.sleep(10); // 模拟请求间隔
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
    }
}